package com.doubledr.light_lock.fragments;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.doubledr.light_lock.R;
import com.doubledr.light_lock.Task.DecryptTask;
import com.doubledr.light_lock.Task.EncryptTask;
import com.doubledr.light_lock.Task.TaskBuilder;
import com.doubledr.light_lock.TextEncryptActivity;
import com.doubledr.light_lock.adapters.MenuAdapter;
import com.doubledr.light_lock.utils.FileManager;
import com.doubledr.light_lock.utils.FileUtil;
import com.doubledr.light_lock.utils.PathManager;
import com.doubledr.light_lock.utils.ShareRefHelper;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoFragment;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link IndexFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class IndexFragment extends TakePhotoFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Context mContext = null;

    public IndexFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SettingsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static IndexFragment newInstance(String param1, String param2) {
        IndexFragment fragment = new IndexFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        //生成模拟数据，后期从服务端读取数据
        int photo = getDrawableRes(this.getContext(),"photo");
        int videlock = getDrawableRes(this.getContext(),"videolock");
        int txtlock = getDrawableRes(this.getContext(),"txtlock");
        //////////////////////////////////////////////////////////////////////
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", getString(R.string.img_encrypt));
        map.put("img",photo+"");
        list.add(map);

        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("title", getString(R.string.en_video));
        map2.put("img",videlock+"");
        list.add(map2);

        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("title", getString(R.string.en_txt));
        map3.put("img",txtlock+"");
        list.add(map3);
        ////////////////////////////////////////////////////////////////

        int photo_unlock = getDrawableRes(this.getContext(),"photo_unlock");
        int video_unlock = getDrawableRes(this.getContext(),"video_unlock");
        int txt_unlock = getDrawableRes(this.getContext(),"txt_unlock");

        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("title", getString(R.string.de_image));
        map4.put("img",photo_unlock+"");
        list.add(map4);

        Map<String, Object> map5 = new HashMap<String, Object>();
        map5.put("title", getString(R.string.de_video));
        map5.put("img",video_unlock+"");
        list.add(map5);

        Map<String, Object> map6 = new HashMap<String, Object>();
        map6.put("title", getString(R.string.de_txt));
        map6.put("img",txt_unlock+"");
        list.add(map6);


        mContext = this.getContext();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        //必须在这个方法后，才能findViewById
        GridView myView = view.findViewById(R.id.menuGridView);
        //设置自定义的adapter
        myView.setAdapter(new MenuAdapter(this.getContext(),list));
        myView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(position == 0 || position == 1 || position == 2){
                    if(ShareRefHelper.getValue(ShareRefHelper.getFileID()).contentEquals("")){
                        Toast toast=Toast.makeText(mContext, R.string.first_setting_pwd,Toast.LENGTH_LONG    );
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        return;
                    }
                }
                //打开相册选择相片
                if(position == 0){
                    openSysAlbum();
                }
                else if(position == 1){
                    //打开选择视频文件
                    chooseVideo();
                }
                else if(position == 2){
                    Intent txtIntent = new Intent(mContext, TextEncryptActivity.class);
                    txtIntent.putExtra("type", "EN");
                    startActivity(txtIntent);
                }
                else if(position == 3){
                    chooseFiles();
                }
                else if(position == 4){
                    chooseFiles();
                }
                else if(position == 5){
                    Intent txtIntent = new Intent(mContext, TextEncryptActivity.class);
                    txtIntent.putExtra("type", "DE");
                    startActivity(txtIntent);
                }

            }
        });
        return view;
    }
    private int getDrawableRes(Context context, String name) {
        String packageName = context.getPackageName();
        return context.getResources().getIdentifier(name, "drawable", packageName);
    }
    private void openSysAlbum() {
        getTakePhoto().onPickFromGallery();
    }
    private void chooseVideo() {
        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent,100);
    }
    private void chooseFiles(){
        Intent intent = new Intent();
        intent.setType("*/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent,101);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        //构造任务参数
        String[] strings = TaskBuilder.getTaskParams(this.getContext(),result.getImage().getOriginalPath());
        //异步执行任务
        EncryptTask newTask = new EncryptTask(this.getContext());
        newTask.execute(strings);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public TakePhoto getTakePhoto() {
        return super.getTakePhoto();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 100){
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                // 视频路径
                final String videoPath = FileUtil.getInstance(this.getContext()).getChooseFileResultPath(uri);
                System.out.println(videoPath);
                if(videoPath!=null){
                    //构造任务参数
                    String[] strings = TaskBuilder.getTaskParams(this.getContext(),videoPath);
                    //异步执行任务
                    EncryptTask newTask = new EncryptTask(this.getContext());
                    newTask.execute(strings);
                }
                else {
                    Toast.makeText(this.getContext(), R.string.getvieopath_failed,Toast.LENGTH_SHORT);
                }
            }
        }
        else if (requestCode == 101){//解密图片、视频
            if (resultCode == RESULT_OK){
                final boolean isInputPwd = false;
                final int pwd = 123;
                Uri uri = data.getData();
                final String filePath = FileUtil.getInstance(this.getContext()).getChooseFileResultPath(uri);
                System.out.println(filePath);
                if(filePath != null){
                    AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
                    builder.setTitle(R.string.input_pwd);
                    View view = getLayoutInflater().inflate(R.layout.alert_input_layout,null);
                    final TextView txtInput = view.findViewById(R.id.edtPwdRq);
                    builder.setView(view);
                    builder.setCancelable(false);
                    builder.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String newPwd = txtInput.getText().toString();
                            if(newPwd.trim().contentEquals("")){
                                Toast toast=Toast.makeText(mContext,R.string.pwd_cannot_null,Toast.LENGTH_SHORT    );
                                toast.setGravity(Gravity.CENTER, 0, 0);
                                toast.show();
                                return;
                            }
                            int pwd = Integer.parseInt(newPwd);
                            DecryptTask newTask = new DecryptTask(mContext,pwd);
                            String targetFilePath = PathManager.getDecrytDir(mContext);
                            String[] strings = {filePath,targetFilePath};
                            newTask.execute(strings);
                        }
                    });
                    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    builder.show();
                }
                else{
                    Toast.makeText(this.getContext(),R.string.getvieopath_failed,Toast.LENGTH_SHORT);
                }

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
